package kr.co.bettersoft.sendme.rest;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import kr.co.bettersoft.sendme.provider.SendMeBlock;
import kr.co.bettersoft.sendme.provider.SendMeCertification;
import kr.co.bettersoft.sendme.provider.SendMeFile;
import kr.co.bettersoft.sendme.provider.SendMeInstall;
import kr.co.bettersoft.sendme.provider.SendMeVoice;
import kr.co.bettersoft.sendme.util.SendMeCommon;
import kr.co.bettersoft.sendme.util.SendMeConstant;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Environment;
import android.util.Log;

/**
 * RESTful 메소드를 구현하는 클래스 이다.
 * 
 * @author blue
 *
 */
public class SendMeAudioMessageRest {
	public static String TAG = SendMeAudioMessageRest.class.getSimpleName();
	
	/**
	 * 음성 메시지를 등록한다 
	 * 
	 * @param sendMeVoice
	 * @return
	 */
	public SendMeVoice registerVoice2(SendMeVoice sendMeVoice) {
		Log.i(TAG, "registerVoice2");
		
		String url = SendMeConstant.SERVER_URL
				+ SendMeConstant.MAPPING_CONTROLLER
				+ SendMeConstant.VOICE_CONTROLLER
				+ SendMeConstant.REGISTER_VOICE;
				
		SendMeVoice result = new SendMeVoice();
		
		/*
		 * 방법 1. 파일 보내기.
		 */
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost ;
		MultipartEntity mpEntity ;
		HttpResponse response = null;
		HttpEntity resEntity = null ;
		
		JSONObject jsonObject;
		
		try {
			httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
			httppost = new HttpPost(url);
			mpEntity = new MultipartEntity();
			
			mpEntity.addPart("idSendMeVoice", new StringBody(sendMeVoice.getIdSendMeVoice()));
			mpEntity.addPart("sender", new StringBody(sendMeVoice.getSender()));
			mpEntity.addPart("activateYn", new StringBody(sendMeVoice.getActivateYn()));
			mpEntity.addPart("modifyDate", new StringBody(sendMeVoice.getModifyDate()));
			mpEntity.addPart("registerDate", new StringBody(sendMeVoice.getRegisterDate()));
			mpEntity.addPart("receiverList", new StringBody(sendMeVoice.getReceiver()));
			mpEntity.addPart("availableDay", new StringBody(sendMeVoice.getAvailableDay()));
			mpEntity.addPart("reservationDate", new StringBody(sendMeVoice.getReservationDate()));
			mpEntity.addPart("reservationTime", new StringBody(sendMeVoice.getReservationTime()));
			mpEntity.addPart("deliveryYn", new StringBody(sendMeVoice.getDeliveryYn()));
			mpEntity.addPart("readYn", new StringBody(sendMeVoice.getReadYn()));
			mpEntity.addPart("fileName", new StringBody(sendMeVoice.getFileName()));		
			
			File file = sendMeVoice.getFile();
			Log.d(TAG,"file length:"+file.length());

			// 이부분의 설정으로 파일을 보낸다.
			ContentBody cbFile = new FileBody(file, "audio/mpeg");			// image/jpeg
			mpEntity.addPart("file", cbFile);  //서버에서 처리해주는 파일이름이 file 이 되겠고, 내가 보내는 파일이 cbFile이다.	
			httppost.setEntity(mpEntity);
			
			response = httpclient.execute(httppost);
			
			resEntity = response.getEntity();
			if (resEntity != null) {
				try {
					String tmpStr = EntityUtils.toString(resEntity);
					jsonObject = new JSONObject(tmpStr);
					result.setResult(jsonObject.getString("result"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			httpclient.getConnectionManager().shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	/**
	 * 받은 음성메시지 목록을 가져온다		selectVoiceList
	 *   상대방이 프로필을 설정한 경우 프로필 명도 가져온다.
	 *    프로필을 설정하지 않아 정보가 없을때는 "미상" 으로 세팅한다
	 *   (나중에 메시지를 저장할때 프로필 명을 함께 저장하도록 한다.)
	 * 
	 * @param 
	 * @return
	 */
	public ArrayList<SendMeVoice> selectVoiceList(SendMeVoice sendMeVoice) {
		Log.i(TAG, "selectVoiceList");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.VOICE_CONTROLLER
			+ SendMeConstant.SELECT_VOICE_LIST;
		
		ArrayList<SendMeVoice> result = null;
		
		try {
			JSONObject parameterJsonObject = new JSONObject();
//			Log.d(TAG,"sendMeVoice.getReceiver():"+sendMeVoice.getReceiver());
			parameterJsonObject.put("receiver", sendMeVoice.getReceiver());				//			receiver : 받는 사용자 휴대전화번호.
			parameterJsonObject.put("deliveryYn", sendMeVoice.getDeliveryYn());			//			deliveryYn : 발송 여부.('Y')
			parameterJsonObject.put("activateYn", sendMeVoice.getActivateYn());			//			activateYn : 활성화 여부('Y')
		
			
			String resultStr = this.requestToServer(url, parameterJsonObject.toString());		
//			Log.d(TAG,"resultStr:"+resultStr);			
			
			JSONArray resultJsonArray = new JSONArray(resultStr);
			result = new ArrayList<SendMeVoice>();		
			
			// 출력용 시간 포맷
			SimpleDateFormat receiveMessageDateSimpleDateFormat = SendMeConstant.receiveMessageDateSimpleDateFormat;
			// 일반 시간 포맷
			SimpleDateFormat commonDateSimpleDateFormat = SendMeConstant.commonDateSimpleDateFormat;
			
			String tempDate;		// 받아서
			Date date;				// Date 타입으로
			String sdfDate;			// 원하는 포맷으로
			
			SendMeCommon sendMeCommon = new SendMeCommon();
			SendMeConstant sendMeConstant = new SendMeConstant();
			
			// 유효 기간
			String AVAILABLE_DAY = sendMeConstant.AVAILABLE_DAY;
			// 만료일
			String expiredDate;
			Calendar calendar;
			
			
			for(int i=0; i<resultJsonArray.length(); i++){				
				JSONObject resultJsonObject = resultJsonArray.getJSONObject(i);
				
				SendMeVoice tempSendMeVoice = new SendMeVoice();
				
				/*
				 * "readYn":"N",
				 * 
				 * "recognitionModifyDate":"2014-02-05 17:30:39"},			// readYn. Y일때 읽은시간. N일때 최초 등록시간. 일때는 무시.
				 */
				
				tempSendMeVoice.setIdSendMeVoice(resultJsonObject.getString("idSendMeVoice"));
				tempSendMeVoice.setSender(resultJsonObject.getString("sender"));
				
				
				tempSendMeVoice.setReservationDate(resultJsonObject.getString("reservationDate"));
				tempSendMeVoice.setReservationTime(resultJsonObject.getString("reservationTime"));
				tempSendMeVoice.setDeliveryYn(resultJsonObject.getString("deliveryYn"));
				
				tempSendMeVoice.setNickName(resultJsonObject.getString("nickName"));
				
				tempSendMeVoice.setModifyDate(resultJsonObject.getString("modifyDate"));
				
				// 등록일 변환해서 넣음.
				tempDate = resultJsonObject.getString("registerDate");		// 받아서
				date = commonDateSimpleDateFormat.parse(tempDate);				// Date 타입으로
				sdfDate = receiveMessageDateSimpleDateFormat.format(date);	// 원하는 포맷으로
				tempSendMeVoice.setRegisterDate(sdfDate);							// 저장
				
				// 파일 정보
				tempSendMeVoice.setIdSendMeFile(resultJsonObject.getString("idSendMeFile"));
				tempSendMeVoice.setFileName(resultJsonObject.getString("fileName"));
				
				// 읽음 여부, 읽은 시각
				String readYn = resultJsonObject.getString("readYn");
				tempSendMeVoice.setReadYn(readYn);
				if(readYn.equals("N")){
					// 읽지 않음
					tempSendMeVoice.setRecognitionModifyDate("읽지 않음");
				}else{
					tempDate = resultJsonObject.getString("recognitionModifyDate");		// 받아서
					date = commonDateSimpleDateFormat.parse(tempDate);			// Date 타입으로
					sdfDate = receiveMessageDateSimpleDateFormat.format(date);	// 원하는 포맷으로
					tempSendMeVoice.setRecognitionModifyDate(sdfDate);					// 저장
				}
				
				/*
				 *  만료일 계산
				 */
				// 현시각 date 로
				String nowTime = sendMeCommon.getCurrentDate();
				calendar = Calendar.getInstance();
				date = commonDateSimpleDateFormat.parse(nowTime);
				calendar.setTime(date);
				Date nowDate = calendar.getTime();
				// 만료일 date로
				calendar = Calendar.getInstance();
				date = commonDateSimpleDateFormat.parse(tempDate);	
				calendar.setTime(date);
				calendar.add(calendar.DATE, Integer.parseInt(AVAILABLE_DAY));				
				Date expireDate = calendar.getTime();		// 만료 일.
				// 남은일.
				long differentTime = expireDate.getTime() - nowDate.getTime();
				long lastDay = differentTime / (1000*60*60*24);
				if( 0 < lastDay ){
					tempSendMeVoice.setExpiredCounter( "D-"+Long.toString(lastDay) );
				}else{
					tempSendMeVoice.setExpiredCounter("기간초과");
				}
				result.add(tempSendMeVoice);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
//		Log.d(TAG,"result="+result.size());
		return result;
	}
	
	
	/**
	 * 받은 음성메시지 목록을 가져온다		selectVoiceList
	 *   상대방이 프로필을 설정한 경우 프로필 명도 가져온다.
	 *    프로필을 설정하지 않아 정보가 없을때는 "미상" 으로 세팅한다
	 *   (나중에 메시지를 저장할때 프로필 명을 함께 저장하도록 한다.)
	 * 
	 * @param 
	 * @return
	 */
	public int selectUnreadVoiceCount(SendMeVoice sendMeVoice) {
		Log.i(TAG, "selectUnreadVoiceCount");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.VOICE_CONTROLLER
			+ SendMeConstant.SELECT_VOICE_LIST;

		int unreadCount = 0;
		
		try {
			JSONObject parameterJsonObject = new JSONObject();
			Log.d(TAG,"receiver:"+sendMeVoice.getReceiver());
			parameterJsonObject.put("receiver", sendMeVoice.getReceiver());				//			receiver : 받는 사용자 휴대전화번호.
			parameterJsonObject.put("deliveryYn", "Y");			//			deliveryYn : 발송 여부.('Y')
			parameterJsonObject.put("activateYn", "Y");			//			activateYn : 활성화 여부('Y')
				
			String resultStr = this.requestToServer(url, parameterJsonObject.toString());		
			Log.d(TAG,"resultStr:"+resultStr);			
			
			JSONArray resultJsonArray = new JSONArray(resultStr);
			
			for(int i=0; i<resultJsonArray.length(); i++){				
				JSONObject resultJsonObject = resultJsonArray.getJSONObject(i);
				/*
				 * "readYn":"N",
				 * 
				 * "recognitionModifyDate":"2014-02-05 17:30:39"},			// readYn. Y일때 읽은시간. N일때 최초 등록시간. 일때는 무시.
				 */				
				// 읽음 여부, 읽은 시각
				String readYn = resultJsonObject.getString("readYn");
				if(readYn.equals("N")){
					unreadCount = unreadCount + 1;
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
				
		return unreadCount;
	}
	
	
	/**
	 * 받은 음성 메시지 파일 다운로드		selectFile
	 * 
	 * @param 
	 * @return
	 */
	public String selectFile(SendMeFile sendMeFile) {
		Log.i(TAG, "selectFile");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.FILE_CONTROLLER
			+ SendMeConstant.SELECT_FILE;
		
		String result = null;
		
		try {
			JSONObject parameterJsonObject = new JSONObject();
			
			parameterJsonObject.put("idSendMeFile", sendMeFile.getIdSendMeFile());
			//			parameterJsonObject.put("activateYn", "Y");
			parameterJsonObject.put("sendMeVoiceIdSendMeVoice", sendMeFile.getSendMeVoiceIdSendMeVoice());
			parameterJsonObject.put("sendMeVoiceSender", sendMeFile.getSendMeVoiceSender());

			byte[] resultByte = this.requestFileToServer(url, parameterJsonObject.toString());
			//			Log.d(TAG,"resultStr:"+resultByte);		// ""
//			Log.d(TAG,"resultStr.length():"+resultByte.length);		// 0

			String fileName = sendMeFile.getFileName();
			String fileFullPath = downloadMP3FileName(fileName);
			//			Log.d(TAG,"fileFullPath:"+fileFullPath);

			File createFile = new File(fileFullPath);		// 생성 필요할지도 모름.

			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileFullPath));
			bos.write(resultByte);
			bos.flush();
			bos.close();
			result = fileFullPath;
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public String downloadMP3FileName(String fileName){
		// 디렉토리 없으면 생성
		File file = new File(Environment.getExternalStorageDirectory().getPath(), SendMeConstant.APPLICATION_AUDIO_DOWNLOAD_DIRECTORY);
		if(!file.exists()){
			file.mkdirs();
		}
		return Environment.getExternalStorageDirectory() + SendMeConstant.APPLICATION_AUDIO_DOWNLOAD_DIRECTORY + "/" + fileName;		
	}
	
	
	/**
	 * 음성 메시지를 삭제한다		updateDeactivate
	 *  받은 메시지 삭제, 예약 메시지 삭제 등.
	 * @param sendMeVoice
	 * @return
	 */
	public SendMeVoice updateDeactivate(SendMeVoice sendMeVoice) {
		Log.i(TAG, "updateDeactivate");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.VOICE_CONTROLLER
			+ SendMeConstant.UPDATE_DEACTIVATE;
		
		SendMeVoice result = new SendMeVoice();
		
		try {
			JSONObject parameterJsonObject = new JSONObject();
			parameterJsonObject.put("idSendMeVoice", sendMeVoice.getIdSendMeVoice());
			parameterJsonObject.put("activateYn", sendMeVoice.getActivateYn());
			parameterJsonObject.put("modifyDate", sendMeVoice.getModifyDate());
			
			String resultStr = this.requestToServer(url, parameterJsonObject.toString());
//			Log.d(TAG,"resultStr:"+resultStr);
			JSONObject resultJsonObject = new JSONObject(resultStr);
			result.setResult(resultJsonObject.getString("result"));		
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	/**
	 * 사용자가 예약 발송한 음성 메시지 목록을 가져 온다.		selectUserReservationList
	 * 
	 * @param 
	 * @return
	 */
	public ArrayList<SendMeVoice> selectUserReservationList(SendMeVoice sendMeVoice) {
		Log.i(TAG, "selectUserReservationList");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.VOICE_CONTROLLER
			+ SendMeConstant.SELECT_USER_RESERVATION_LIST;
		
		ArrayList<SendMeVoice> result = null;
	
		try {
			JSONObject parameterJsonObject = new JSONObject();
			
			parameterJsonObject.put("sender", sendMeVoice.getSender());					//	음성 메시지 보내는 사용자 휴대전화번호.	
			parameterJsonObject.put("deliveryYn", sendMeVoice.getDeliveryYn());			//	발송 여부.('N')	
			parameterJsonObject.put("activateYn", sendMeVoice.getActivateYn());			//	활성화 여부('Y')	
			
			String resultStr = this.requestToServer(url, parameterJsonObject.toString());
//			Log.d(TAG,"resultStr:"+resultStr);
			JSONArray resultJsonArray = new JSONArray(resultStr);
			result = new ArrayList<SendMeVoice>();		
			
			SimpleDateFormat receiveMessageDateSimpleDateFormat = SendMeConstant.receiveMessageDateSimpleDateFormat;
			// 일반 시간 포맷
			SimpleDateFormat commonDateSimpleDateFormat = SendMeConstant.commonDateSimpleDateFormat;
			// 일반 예약 시간 포맷
			SimpleDateFormat commonReservationDateSimpleDateFormat = SendMeConstant.commonReservationDateSimpleDateFormat;
			
			String reservationFullDate;
			
			String tempDate;		// 받아서
			Date date;				// Date 타입으로
			String sdfDate;			// 원하는 포맷으로
			
			SendMeCommon sendMeCommon = new SendMeCommon();
			SendMeConstant sendMeConstant = new SendMeConstant();
			
			// 유효 기간
			String AVAILABLE_DAY = sendMeConstant.AVAILABLE_DAY;
			// 만료일
			String expiredDate;
			Calendar calendar;
			Log.d(TAG,"resultJsonArray.length():"+resultJsonArray.length());
			for(int i=0; i<resultJsonArray.length(); i++){				
				JSONObject resultJsonObject = resultJsonArray.getJSONObject(i);
				
				SendMeVoice tempSendMeVoice = new SendMeVoice();
				
				// 기본 정보
				tempSendMeVoice.setIdSendMeVoice(resultJsonObject.getString("idSendMeVoice"));
				tempSendMeVoice.setSender(resultJsonObject.getString("sender"));
				
				// 예약 일시
				reservationFullDate = resultJsonObject.getString("reservationDate") + " " + resultJsonObject.getString("reservationTime");
				date = commonReservationDateSimpleDateFormat.parse(reservationFullDate);				// Date 타입으로
				sdfDate = receiveMessageDateSimpleDateFormat.format(date);					// 원하는 포맷으로
				tempSendMeVoice.setReservationFullDate(sdfDate);							// 저장
				
				tempSendMeVoice.setReservationDate(resultJsonObject.getString("reservationDate"));
				tempSendMeVoice.setReservationTime(resultJsonObject.getString("reservationTime"));
				
				// 파일 정보
				tempSendMeVoice.setIdSendMeFile(resultJsonObject.getString("idSendMeFile"));
				tempSendMeVoice.setFileName(resultJsonObject.getString("fileName"));
				
				// 수정일.
				tempSendMeVoice.setModifyDate(resultJsonObject.getString("modifyDate"));
				
				// 등록일. 변환해서 넣음
				tempDate = resultJsonObject.getString("registerDate");		// 받아서
				date = commonDateSimpleDateFormat.parse(tempDate);				// Date 타입으로
				sdfDate = receiveMessageDateSimpleDateFormat.format(date);	// 원하는 포맷으로
				tempSendMeVoice.setRegisterDate(sdfDate);							// 저장
				
				// 친구 정보(전번. 그룹일때는 그룹으로 표시)
				String receiverCount = resultJsonObject.getString("receiverCount");
				tempSendMeVoice.setReceiverCount(receiverCount);
				if(receiverCount.equals("1")){			// 1명 일때
					tempSendMeVoice.setReceiver(resultJsonObject.getString("receiver"));
				}else{										// 2명 이상일때
					tempSendMeVoice.setReceiver("그룹");		// 보여주기용도 ###  그룹일때 receiver 값이 없어서 다른 값 부여..
				}
				result.add(tempSendMeVoice);
			}
//			Log.d(TAG,"result:"+result.size());
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	/**
	 * 예약 발송 음성 메시지를 발송 한다.
	 * 
	 * @param sendMeVoice
	 * @return
	 */
	public SendMeVoice updateDeliveryYn(SendMeVoice sendMeVoice) {
		Log.i(TAG, "updateDeliveryYn");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.VOICE_CONTROLLER
			+ SendMeConstant.UPDATE_DELIVERY_YN;
		
		SendMeVoice result = new SendMeVoice();
//		updateDeliveryYn		
//		idSendMeVoice : 음성 메시지 아이디.	
//		deliveryYn : 발송 여부('Y')	
//		activateYn : 활성화 여부('Y')	
//		modifyDate : 수정 일자.	
		try {
			JSONObject parameterJsonObject = new JSONObject();
			parameterJsonObject.put("idSendMeVoice", sendMeVoice.getIdSendMeVoice());		// 음성 메시지 아이디.	
			parameterJsonObject.put("deliveryYn", sendMeVoice.getDeliveryYn());				// 발송 여부('Y')	
			parameterJsonObject.put("activateYn", sendMeVoice.getActivateYn());				// 활성화 여부('Y')	
			parameterJsonObject.put("modifyDate", sendMeVoice.getModifyDate());				// 수정 일자.	
			
			String resultStr = this.requestToServer(url, parameterJsonObject.toString());
			Log.d(TAG,"resultStr:"+resultStr);
			JSONObject resultJsonObject = new JSONObject(resultStr);
			result.setResult(resultJsonObject.getString("result"));		
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	/**
	 * http protocal 을 사용하는 서버 요청 공통 메소드.
	 * 요청 후 결과를 json string 으로 받아서 반환 한다.
	 * 
	 * @param url
	 * @param inputJsonString
	 * @return
	 */
	public String requestToServer(String url, String inputJsonString) {
		Log.i(TAG, "requestToServer");
		
		String result = "";
		
		try {
			URL postUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(inputJsonString.getBytes());
	        os.flush();
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        		result = bufferedReader.readLine();
	        	}else{
	        		Log.d(TAG,"connection.getResponseCode():"+connection.getResponseCode());		// 404  json 으로 받았는데 안에 byte 가 들어있다면 parsing 해서 사용할수 있을 것..
	        	}
	        }
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	/**
	 * http protocal 을 사용하는 서버 요청 공통 메소드.
	 * 요청 후 결과를 json string 으로 받아서 반환 한다.
	 * 
	 * @param url
	 * @param inputJsonString
	 * @return
	 */
	public byte[] requestFileToServer(String url, String inputJsonString) {
		Log.i(TAG, "requestFileToServer");
		
		byte[] result = null;

		try {
			URL postUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(inputJsonString.getBytes());
	        os.flush();
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		
	        		
	        	     InputStream stream = connection.getInputStream();
	        	     result = IOUtils.toByteArray(stream);
	        		
//	        		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//	        		result = bufferedReader.readLine();
	        	}else{
	        		Log.d(TAG,"connection.getResponseCode():"+connection.getResponseCode());		// 404  json 으로 받았는데 안에 byte 가 들어있다면 parsing 해서 사용할수 있을 것..
	        	}
	        }
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
}
